//
//  BKIntegralAllVoucherController.m
//  bestkeep
//
//  Created by yons on 16/12/7.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKIntegralAllVoucherController.h"
#import "BKMainCommon.h"
#import "BKSignVoucherCollectionViewCell.h"
#import "BKExchangeVoucherViewController.h"
#import "BKintegralModel.h"
#import "BKIntegralCollectionModel.h"
#import "MJExtension.h"

@interface BKIntegralAllVoucherController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) ExceptionView *exceptionView;
@property (nonatomic,strong) NSMutableArray   * marr_collectionCell;
@property (nonatomic,strong) BKintegralModel * model;//Model

@end

@implementation BKIntegralAllVoucherController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setProperty];
    [self createUI];
    [self check_NetWork];
    
}

#pragma mark==================setProperty======================
-(void)setProperty{
    
    self.title = @"全部优惠券";
    self.view.backgroundColor=RGB(242, 242, 242);
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    
}

-(void)createUI{
    
    [self.view addSubview:self.collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(self.view.mas_top).offset(0);
        make.right.bottom.left.mas_equalTo(self.view);
    }];
    
}

#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            [self BK_getData_IntegralAllVoucher_FromNetWork];
            
        }
            break;
            
        default: {
            [HUD dismiss];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
            
        }
            break;
    }
}

#pragma mark ---------------数据请求-------------------

-(void)BK_getData_IntegralAllVoucher_FromNetWork{
    [LoadingView loadingShoppingCartInView:self.view];
    [BKIntegralCommon getUserCheckInfo:^(BOOL isSucess, id obj, NSError *error) {
        [LoadingView dismiss];
        if (isSucess) {
            NSDictionary * dic =(NSDictionary *)obj;
            _model =[BKintegralModel mj_objectWithKeyValues:dic];
            [_collectionView reloadData];
        }
        if (error) {
            ExceptionCodeType errorType;
            if (error.code == -1009) {
                errorType = ExceptionCodeTypeNoNetwork;
            } else if (error.code == -1001){
                errorType = ExceptionCodeTypeRequestFailed;
            }else if(error.code == 502 || error.code == 404){
                errorType =  ExceptionCodeTypeServerError;
            } else {
                errorType = ExceptionCodeTypeFailedToLoad;
            }
            
            self.exceptionView = [ExceptionView exceptionViewWithType:errorType];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:errorType handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self BK_getData_IntegralAllVoucher_FromNetWork];
            }];
            
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
            
        }
    }];
}
#pragma mark - <UICollectionViewDataSource>
// 设置headerView和footerView的
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
    }
    return nil ;
}
// 设置section头视图的参考大小，与tableheaderview类似
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    BKIntegralCollectionModel * model=self.marr_collectionCell[section];
    return model.header_size;
}


- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout colorForSectionAtIndex:(NSInteger)section{
    BKIntegralCollectionModel * model=self.marr_collectionCell[section];
    return model.section_color;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    BKIntegralCollectionModel * model=self.marr_collectionCell[indexPath.section];
    return model.item_size;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    BKIntegralCollectionModel * model=self.marr_collectionCell[section];
    return model.section_Edge;
}
// 两个cell之间的最小间距，是由API自动计算的，只有当间距小于该值时，cell会进行换行
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    BKIntegralCollectionModel * model=self.marr_collectionCell[section];
    return model.interitemSpacing;
}
// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    BKIntegralCollectionModel * model=self.marr_collectionCell[section];
    return model.lineSpacing;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    BKIntegralCollectionModel * model=self.marr_collectionCell[section];
    if ([model.id_dentifier isEqualToString:@"BKSignVoucherCollectionViewCell"]) {
        return _model.couponList.count;
    }
    return 0;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.marr_collectionCell.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell*  cell=nil;
    BKIntegralCollectionModel * model=self.marr_collectionCell[indexPath.section];
    IF(model.id_dentifier, cell =[collectionView dequeueReusableCellWithReuseIdentifier:model.id_dentifier forIndexPath:indexPath], )
    if ([model.id_dentifier isEqualToString:@"BKSignVoucherCollectionViewCell"]) {
        if (_model.couponList.count>0) {
            [(BKSignVoucherCollectionViewCell*)cell relayOutUI:_model.couponList[indexPath.row]];
        }
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    BKIntegralCollectionModel * model=self.marr_collectionCell[indexPath.section];
    if ([model.id_dentifier isEqualToString:@"BKSignVoucherCollectionViewCell"]) {
        BKExchangeVoucherViewController *exchangeVoucherVC = [[BKExchangeVoucherViewController alloc]init];
        BKSignVoucherModel * model = [_model.couponList objectAtIndex:(indexPath.row)];
        exchangeVoucherVC.couponId=model.couponId;
        exchangeVoucherVC.view.backgroundColor = [UIColor whiteColor];
        [self.navigationController pushViewController:exchangeVoucherVC animated:YES];

    }
}



-(UICollectionView *)collectionView{
    if (!_collectionView) {
        //创建一个layout布局类
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView=[[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor=RGB(242, 242, 242);
        _collectionView.dataSource=self;
        _collectionView.delegate=self;
        [_collectionView registerClass:NSClassFromString(@"BKSignVoucherCollectionViewCell") forCellWithReuseIdentifier:@"BKSignVoucherCollectionViewCell"];
    }
    return _collectionView;
}

-(NSMutableArray *)marr_collectionCell{
    if (!_marr_collectionCell) {
        _marr_collectionCell=[[NSMutableArray alloc]init];
        
        BKIntegralCollectionModel * model1=[[BKIntegralCollectionModel alloc]init];
        model1.header_size=CGSizeMake(0, 0);
        model1.item_size=CGSizeMake((SCREENWIDTH-2.0*ApplicationBackGauge)/2.0-5.0f,110+10);
        model1.section_color=[UIColor clearColor];
        model1.section_Edge=UIEdgeInsetsMake(0, ApplicationBackGauge, 25, ApplicationBackGauge);
        model1.interitemSpacing=0.1;
        model1.lineSpacing=0.1;
        model1.isHaveHeader=NO;
        model1.id_dentifier=@"BKSignVoucherCollectionViewCell";
        [_marr_collectionCell addObject:model1];
    }
    return _marr_collectionCell;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

























